package uk.co.biggroup.lotto.syndicate;

import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
 
import javax.xml.parsers.ParserConfigurationException;
 
import org.apache.http.client.ClientProtocolException;
import org.htmlcleaner.CleanerProperties;
import org.htmlcleaner.HtmlCleaner;
import org.htmlcleaner.TagNode;
import org.htmlcleaner.XPatherException;
import org.xml.sax.SAXException;

import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

public class Draws extends ListActivity {

	public static final String PREFS_NAME = "Settings";
	private static ArrayList<Draw> itemsy;
	public static int error;
	static Draw[] drawsArr;
	static String balance;
	static String lastUpdate;
	static int acstatus;
	static String acTextStatus = "";
	TextView tlastupdate;
	TextView tbalance;
	TextView tstatus;

	@Override
	public void onCreate(Bundle icicle) {
		super.onCreate(icicle);
		setContentView(R.layout.draws);

		tstatus = (TextView) this.findViewById(R.id.status);
		tbalance = (TextView) this.findViewById(R.id.balance);
		tlastupdate = (TextView) this.findViewById(R.id.lastupdate);

		new DownloadGroups().execute("");

	}
	
	public void onListItemClick(ListView parent, View v, int position, long id) {
		final Bundle bundle = new Bundle();
		bundle.putInt("drawid", itemsy.get(position).getId());
		bundle.putInt("acstatus", acstatus);
		bundle.putInt("type", itemsy.get(position).getType());
		bundle.putString("acTextStatus", acTextStatus);
		bundle.putString("balance", balance);
		bundle.putString("lastupdate", lastUpdate);
		bundle.putString("luckynumbers", itemsy.get(position).getResult());		
		bundle.putString("status", itemsy.get(position).getStatus());
		bundle.putString("date", itemsy.get(position).getDate());		
		Logh.i("JHubsList button pressed");
		Intent myIntents = new Intent(parent.getContext(), Numbers.class);
		myIntents.putExtras(bundle);
		startActivityForResult(myIntents, 0);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		menu.add(1, 2, 1, "Refresh").setIcon(R.drawable.ic_menu_refresh);
		return super.onCreateOptionsMenu(menu);
	}

	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case 2:
			new DownloadGroups().execute("");
			break;
		}
		return true;
	}

	class IconicAdapter extends ArrayAdapter<Draw> {

		private ArrayList<Draw> itemsy;

		IconicAdapter(Context context, int textViewResourceId,
				ArrayList<Draw> itemsyx) {
			super(context, textViewResourceId, itemsyx);
			this.itemsy = itemsyx;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			LayoutInflater inflater = getLayoutInflater();
			View drawitem = inflater.inflate(R.layout.drawitem, parent, false);
			TextView date = (TextView) drawitem.findViewById(R.id.date);
			TextView status = (TextView) drawitem.findViewById(R.id.status);
			TextView result = (TextView) drawitem.findViewById(R.id.result);
			ImageView icon = (ImageView) drawitem.findViewById(R.id.icon);
			Draw d = itemsy.get(position);
			if (d != null) {
				date.setText(d.getDate());
				status.setText(d.getStatus());
				result.setText(d.getResult());
				if (d.getType() == 2) {
					icon.setImageResource(R.drawable.euro_logoballsm);
				} else if (d.getType() == 1) {
					icon.setImageResource(R.drawable.lotto_logoballsm);
				} else {
					icon.setImageResource(R.drawable.lotto_logoballsm);
				}
			}
			return (drawitem);
		}
	}

	private class DownloadGroups extends AsyncTask<String, Void, String> {

		ProgressDialog dialog;

		@Override
		protected String doInBackground(String... params) {
			error = 0;
			try {
				getHtml();
			} catch (ClientProtocolException e) {
				Logh.i("ClientProtocolException");
			} catch (IOException e) {
				Logh.i("IOException");
			} catch (XPatherException e) {
				Logh.i("XPatherException");
			} catch (ParserConfigurationException e) {
				Logh.i("ParserConfigurationException");
			} catch (SAXException e) {
				Logh.i("SAXException");
			}
			return null;
		}

		@Override
		protected void onPostExecute(String result) {
			dialog.dismiss();

			if (error == 1) {
				Intent intent = new Intent();
				intent.setClass(Draws.this, Welcome.class);
				startActivity(intent);
				finish();
			}

			switch (acstatus) {
			case 1:
				acTextStatus = "OK - IN GAME ";
				tstatus.setText(acTextStatus);
				break;
			case 2:
				acTextStatus = "NOT INCLUDED ";
				tstatus.setText(acTextStatus);
				break;
			case 3:
				acTextStatus = "TOP UP BALANCE! ";
				tstatus.setText(acTextStatus);
				break;
			case 4:
				acTextStatus = "OUT OF THE GAME ";
				tstatus.setText(acTextStatus);
				break;
			}

			tbalance.setText(balance + " ");
			tlastupdate.setText(lastUpdate + " ");

			Draws.this.setListAdapter(new IconicAdapter(Draws.this,
					R.layout.drawitem, itemsy));
		}

		@Override
		protected void onPreExecute() {
			dialog = ProgressDialog.show(Draws.this, "",
					"Wait, Accessing data...", true);
		}

		@Override
		protected void onProgressUpdate(Void... values) {

		}

		public void getHtml() throws ClientProtocolException, IOException,
				XPatherException, ParserConfigurationException, SAXException,
				IOException, XPatherException {

			String AUDITIONS_XPATH = "//draws/draw/@date";
			String LINKS_XPATH = "//draws/draw/@id";
			String RESULT_XPATH = "//draws/draw/@result";
			String NUMBERS_XPATH = "//draws/draw[@id='6']/lines//line/@numbers";

			String STATUS_XPATH = "//draws/draw/@status";
			String TYPE_XPATH = "//draws/draw/@type";

			String BALANCE_XPATH = "//draws/@amount";
			String UPDATED_XPATH = "//draws/@updated";
			String ACSTATUS_XPATH = "//draws/@accountstatus";
			String ERROR_XPATH = "//error/@msg";

			TagNode node;

			ArrayList<String> titlesList = new ArrayList<String>();
			ArrayList<String> linksList = new ArrayList<String>();
			ArrayList<String> statusList = new ArrayList<String>();
			ArrayList<String> typeList = new ArrayList<String>();
			ArrayList<String> resultsList = new ArrayList<String>();
			ArrayList<String> numbersList = new ArrayList<String>();

			SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
			String tokenCheck = settings.getString("token", "");

			URL url = new URL(
					"http://syndicates.biggroup.co.uk/MyAccount/DownloadXML.aspx?t="
							+ tokenCheck);
			URLConnection conn = url.openConnection();

			HtmlCleaner cleaner = new HtmlCleaner();
			CleanerProperties props = cleaner.getProperties();
			props.setAllowHtmlInsideAttributes(true);
			props.setAllowMultiWordAttributes(true);
			props.setRecognizeUnicodeChars(true);
			props.setTranslateSpecialEntities(true);
			props.setOmitComments(true);

			node = cleaner.clean(new InputStreamReader(conn.getInputStream()));

			Object[] info_nodes = node.evaluateXPath(AUDITIONS_XPATH);
			Object[] links_nodes = node.evaluateXPath(LINKS_XPATH);
			Object[] results_nodes = node.evaluateXPath(RESULT_XPATH);
			Object[] numbers_nodes = node.evaluateXPath(NUMBERS_XPATH);

			Object[] status_nodes = node.evaluateXPath(STATUS_XPATH);
			Object[] type_nodes = node.evaluateXPath(TYPE_XPATH);

			Object[] error_nodes = node.evaluateXPath(ERROR_XPATH);
			Object[] balance_nodes = node.evaluateXPath(BALANCE_XPATH);
			Object[] update_nodes = node.evaluateXPath(UPDATED_XPATH);
			Object[] acstatus_nodes = node.evaluateXPath(ACSTATUS_XPATH);

			if (error_nodes.length > 0) {
				for (Object linkNode : error_nodes) {
					String s = linkNode.toString();
					error = 1;
					Logh.i(s);
				}
			}

			if (acstatus_nodes.length > 0) {
				for (Object linkNode : acstatus_nodes) {
					String st = linkNode.toString();
					acstatus = Integer.parseInt(st);
					Logh.i(st);
				}
			}

			if (update_nodes.length > 0) {
				for (Object linkNode : update_nodes) {
					String s = linkNode.toString();
					lastUpdate = s;
					Logh.i(s);
				}
			}

			if (balance_nodes.length > 0) {
				for (Object linkNode : balance_nodes) {
					String s = linkNode.toString();
					balance = s;
					Logh.i(s);
				}
			}

			if (numbers_nodes.length > 0) {
				for (Object linkNode : numbers_nodes) {
					String s = linkNode.toString();
					numbersList.add(s);
					Logh.i(s);
				}
			}

			if (info_nodes.length > 0) {
				for (Object linkNode : info_nodes) {
					String s = linkNode.toString();
					titlesList.add(s);
					Logh.i(s);
				}
			}

			if (links_nodes.length > 0) {
				for (Object linksNode : links_nodes) {
					String s = linksNode.toString();
					linksList.add(s);
					Logh.i(s);
				}
			}

			if (status_nodes.length > 0) {
				for (Object idsNode : status_nodes) {
					String s = idsNode.toString();
					statusList.add(s);
					Logh.i(s);
				}
			}

			if (type_nodes.length > 0) {
				for (Object typeNode : type_nodes) {
					String s = typeNode.toString();
					String lower = s.toLowerCase();
					if (lower.equals("euromillions")){
						typeList.add("2");
					} else if (lower.equals("lotto")){	
						typeList.add("1");
					} else {
						typeList.add("3");
					}
					Logh.i(s);
				}
			}

			if (results_nodes.length > 0) {
				for (Object resNode : results_nodes) {
					String s = resNode.toString();
					resultsList.add(s);
					Logh.i(s);
				}
			}

			itemsy = new ArrayList<Draw>();
			int itemCount = titlesList.size();
			drawsArr = new Draw[itemCount];
			for (int i = 0; i < itemCount; i++) {
				Logh.i("JSONARRAY", "LOOPh");
				drawsArr[i] = new Draw(Integer.parseInt(linksList.get(i)),
						titlesList.get(i), statusList.get(i), Integer
								.parseInt(typeList.get(i)), resultsList.get(i));
				itemsy.add(drawsArr[i]);
			}

		}
	}
}
